<?php

namespace frontend\components\actions;

use common\helpers\VoteHelper;
use common\models\c2\entity\ActivityPlayerModel;
use common\models\c2\entity\ActivityPlayerVoteRecordModel;
use common\models\c2\statics\ActivityPlayerState;
use common\models\c2\statics\VoteType;
use common\models\c2\statics\Whether;
use cza\base\models\statics\ResponseDatum;
use Yii;
use yii\base\InvalidConfigException;
use yii\web\HttpException;
use yii\web\NotFoundHttpException;
use yii\web\Response;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/10 0010
 * Time: 下午 15:34
 */
class VoteAction extends \yii\base\Action
{
    public $playerId;

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        // if (!$redis->getIsActive()) {
        //     // throw new InvalidConfigException('Require Sms Component Support!');
        //     throw new HttpException(500,Yii::t('app.c2', 'Require Redis Component Support!'));
        // }
    }

    public function run()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $params = Yii::$app->request->post();
        $playerModel = ActivityPlayerModel::findOne($params['id']);
        if ($playerModel->state == ActivityPlayerState::STATE_NOT_CHECK) {
            return ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Player disable.')], false);
        }
        $activityModel = $playerModel->activity;
        if ($activityModel->is_released != Whether::TYPE_YES || time() > strtotime($activityModel->end_at)) {
            return ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Activity disable.')], false);
        }
        $user = \Yii::$app->user->identity;
        $key = K_VOTED . $user->id . '_' . $playerModel->id . '_' . date('Y-m-d', time());
        $redis = \Yii::$app->redis;
        $votedNum = $redis->get($key);
        if ($votedNum < $activityModel->vote_number_limit) {
            $attributes = [
                'type' => VoteType::TYPE_FREE,
                'user_id' => $user->id,
                'activity_player_id' => $playerModel->id,
                'vote_number' => 1,
                'order_id' => 0,
                'gift_id' => 0,
                'remote_ip' => Yii::$app->request->userIP,
            ];
            $model = new ActivityPlayerVoteRecordModel();
            $model->setAttributes($attributes);
            if ($model->save()) {

                $playerModel->updateCounters(['free_vote_number' => 1]);
                $playerModel->updateCounters(['total_vote_number' => 1]);
                $activityModel->updateCounters(['vote_number' => 1]);
                $user->updateCounters(['score' => 1]);

                $redis->incr($key);
                $redis->expire($key, 60 * 60 * 24);

                VoteHelper::setActivityPlayerRank($redis, $playerModel);

                // $kActivity = K_ACTIVITY_RANK . $playerModel->activity_id;
                // $kPlayer = K_PLAYER . $playerModel->id;
                // $redis->executeCommand('ZADD', [$kActivity, $playerModel->total_vote_number, $kPlayer]);

                $responseData = ResponseDatum::getSuccessDatum([
                    'message' => Yii::t('app.c2', 'Vote Success')
                ], $playerModel);
            } else {
                $responseData = ResponseDatum::getErrorDatum(['message' => Yii::t('app.c2', 'Vote Fail')], false);
            }

        } else {
            $responseData = ResponseDatum::getErrorDatum([
                'message' => Yii::t('app.c2', 'You can vote {s1} once day.', [
                    's1' => $activityModel->vote_number_limit
                ])
            ], false);
        }
        return $responseData;
    }

    protected function beforeRun()
    {
        // if (Yii::$app->user->isGuest) {
        //     Yii::info('before vote');
        //     if(!Yii::$app->wechat->isAuthorized()) {
        //         Yii::info('在微信客户端');
        //         return Yii::$app->wechat->authorizeRequired()->send();
        //     }
        // }
        return parent::beforeRun(); // TODO: Change the autogenerated stub
    }
}